package thread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @description: 模拟两个战士同时砍一个怪物，怪物的血掉为0，即判定死亡
 * @author: apple
 * @date:  2021/11/28 7:08 下午
 * @version 1.0
 **/
public class GameTest {


    public static void main(String[] args) {

        // boss对象
        Boss b = new Boss();
        // 玩家1
        GamePlayer g1 = new GamePlayer(100 , "玩家1" , b);
        Thread t1 = new Thread(g1);

        // 玩家2
        GamePlayer g2 = new GamePlayer(100 , "玩家2" , b);
        Thread t2 = new Thread(g2);

        t1.start();
        t2.start();


    }
}

/*
玩家类
 */
class GamePlayer implements Runnable {

    // 攻击力
    private int attack;

    // 玩家的名称
    private String name;

    // 被攻击的怪物
    private Boss boss;

    private static final ReentrantLock LOCK = new ReentrantLock(true);

    public GamePlayer(int attack , String name , Boss b) {
        this.attack = attack;
        this.name = name;
        this.boss = b;
    }

    // 攻击boss方法
    public void attackBoss(Boss boss) {

        while(true) {
            try {
                LOCK.lock();
                if (!boss.isDead()) {
                    boss.shangxue(attack);
                    System.out.println(this.name + "攻击" + boss.getName() + "还剩下：" + boss.getHp() + "的血");
                }
                if (boss.isDead()) {
                    System.out.println("怪物已经死亡");
                    break;
                }
            } finally {
                LOCK.unlock();
            }
        }

    }

    @Override
    public void run() {

        attackBoss(boss);

    }
}

/*
怪物类
 */
class Boss {

    // 怪物的血量
    private int hp = 1000;

    private String name = "千年火龙神";

    public void shangxue(int attack) {
        hp -= attack;

    }

    public int getHp() {

        return hp;
    }

    public String getName() {
        return name;
    }

    public boolean isDead() {

        return hp <= 0;
    }
}